$m(function(args){
    var $this = this.element, that = this;
    var callback = args.callback;
    var tree = $this.find(".app-tree");
    // 获取ai空间id
    var aiWorkspaceId = $this.find('.tempo-ai-bi-relation-ai-info').attr('aiWorkspaceId');
    // 获取ai应用id
    var aiAppId = $this.find('.tempo-ai-bi-relation-ai-info').attr('aiAppId');
    // 获取ai流程id
    var aiFlowId = $this.find('.tempo-ai-bi-relation-ai-info').attr('aiFlowId');


    var initDialog = function(){
        $this.dialog({
            title: getI18n("app_add_achievement"),
            height: 500,
            width: 600,
            resizable:false,
            modal : true,
            open:function(){

            },
            close:function(){
                $this.dialog('destroy').remove();
            },
            buttons:[{
                type : "ok",
                click : function(e) {
                    confirmHandle() ? $this.dialog("close") : "";
                }
            },{
                type : "cancel",
                click : function(e) {
                    $this.dialog('close');
                }
            }]
        });
    };

    var initLayout = function(){
        $this.find(".container-layout").layout({
            west : {
                resizable : false,
                size : 220,
                spacing_open : 0,
                closable : false
            }
        });
    };

    var initComponent = function(){
        // 空间搜索
        $this.find(".left-container .search-bar").searchbar({
            width: 200,
            isEnter: true,
            placeholder: getI18n("please_input_name"),
            onSearch: function(text){
                loadBiWorkspaceList({biWorkspaceName: text});
            }
        });
        // 应用搜索
        $this.find(".right-container .search-bar").searchbar({
            width: 340,
            isEnter: true,
            auto: true,
            placeholder: getI18n("please_input_name"),
            onSearch: function(text){
                loadAppTree({
                    biAppName: text,
                    aiWorkspaceId: aiWorkspaceId,
                    aiAppId: aiAppId
                });
            }
        });
    };

    var initEvent = function(){
        // 空间列表单击事件
        $this.find(".wk-list").on("click", "li", function(event){
            var biWorkspaceData = $(this).data("biWorkspaceData");
            if (biWorkspaceData.id && biWorkspaceData.id == "more") {
                return
            }
            $(this).siblings().removeClass("selected");
            $(this).addClass("selected");
            $this.find(".right-container .search-bar").searchbar("clear");
            // 加载应用树
            loadAppTree({
                biWorkspaceId: biWorkspaceData.BI_WORKSPACE_ID,
                biAppName: "",
                aiWorkspaceId: aiWorkspaceId,
                aiAppId: aiAppId
            });
        });
    };

    /**
     * 加载应用树
     * @param param 参数 biWorkspaceId bi空间id biAppName bi应用名称 aiWorkspaceId ai空间id aiAppId ai应用id
     */
    var loadAppTree = function(param){
        $.extend(that.appTreeParam, param);
        if (!that.appTreeParam.biWorkspaceId) {
            return
        }
        appAjax("/api/ai/app/tree-search-bi-app", that.appTreeParam, function(data){
            renderAppTree(data);
            selectAppRender();
        }, 'post');
    };

    var renderAppTree = function(treeData){
        if (tree.data("tempo-gtree")) {
            tree.gtree("destroy");
        }
        tree.gtree({
            data: treeData,
            /**
             * 是否渲染复选框
             */
            isRenderCheckbox:function(nodeData){
                return nodeData.fileType == 'FILE';
            },
            onCheckboxChange:function(nodeData, isChecked, event){
                selectAppRender();
            },
            /**
             * 获取节点图标
             */
            getItemIcon:function(nodeData){
                return 'tempo-api-icon-tree-16 tempo-api-icon-tree-16-position-10'
            },
            /**
             * 获取未展开的文件夹图标
             */
            getFolderCloseIcon:function(nodeData){
                return "tempo-ui-icon-api-folder-close";
            },
            /**
             * 获取展开的文件夹图标
             */
            getFolderOpenIcon:function(nodeData){
                return "tempo-ui-icon-api-folder-open";
            },
            /**
             * 是否叶子节点
             */
            isLeafNode:function(nodeData){
                return nodeData.type == 'visual' && nodeData.fileType == 'FILE';
            }
        });
    };

    var selectAppRender = function(){
        var text = getI18n("app_selected_achievemet_num");
        $this.find(".right-container .footer").html(TempoUtils.replaceArray(text, "<span>" + getCheckedApp().length + "</span>"));
    };

    var loadBiWorkspaceList = function(param){
        var rows = 200;
        appAjax("/api/ai/app/list-allow-search-bi-workspace", $.extend(param, {rows: rows, page: 1, aiWorkspaceId: aiWorkspaceId, aiAppId: aiAppId, aiFlowId: aiFlowId}), function(data){
            renderBiWorkspaceList(data.rows, data.records > rows);
            var text = getI18n("app_wk_total_num");
            $this.find(".left-container .footer").html(TempoUtils.replaceArray(text, "<span>" + data.records + "</span>"));
        },'get');
    };

    var renderBiWorkspaceList = function(BiWorkspaceData, isMore){
        var wkUl = $this.find(".wk-list").empty();
        var ul = $("<ul>"), li;
        var biWorkspaceDataLen = BiWorkspaceData.length;
        for (var i = 0; i < biWorkspaceDataLen; i++) {
            li = $("<li>").data("biWorkspaceData", BiWorkspaceData[i]);
            $("<span>").addClass("icon tempo-api-icon-16 tempo-api-icon-16-position-51")
                .appendTo(li);
            $("<span>").addClass("label")
                .text(BiWorkspaceData[i].BI_WORKSPACE_NAME)
                .attr("title", BiWorkspaceData[i].BI_WORKSPACE_NAME)
                .appendTo(li);
            ul.append(li);
        }
        if (isMore) {
            $("<li class='more'>").data("BiWorkspaceData", {id : "more", name: getI18n("app_more_wk_please_search")})
                .append($("<span>").addClass("line"))
                .append($("<span>").addClass("line-label").text(getI18n("app_more_wk_please_search")))
                .appendTo(ul);
        }
        wkUl.append(ul.children());
    };

    var appAjax = function(url, param, callback, type, isProcess){
        var that = this;
        var process;
        if (isProcess) {
            process = $("<div/>").tempoprogressbar();
        }
        $.ajax({
            url: contextPath + url,
            data: param,
            type: type || 'post',
            complete: function(XMLHttpRequest, textStatus){
                process ? process.tempoprogressbar("destroy") : "";
            },
            success: function(resultData){
                if (resultData.success) {
                    callback.call(that, resultData.data);
                } else {
                    $("<div/>").alert({
                        width: 500,
                        height: 197,
                        msg: resultData.message
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("<div/>").alert({
                    width: 500,
                    height: 197,
                    msg: "Error!"
                });
            }
        });
    };

    var getCheckedApp = function(){
        if (!tree.data("tempo-gtree")) {
            return [];
        }
        return tree.gtree("getChecked");
    };

    var confirmHandle = function(){
        var apps = getCheckedApp();
        if (apps.length == 0) {
            $("<div/>").alert({
                width: 500,
                height: 197,
                msg: getI18n("app_please_select_achievement")
            });
            return false;
        }
        callback(apps);
        return true;
    };

    var getI18n = function(code){
        if (!that.i18n) {
            that.i18n = $("#tempo-app-index-i18n");
        }
        return that.i18n.attr("_" + code);
    };

    var init = function(){
        that.appTreeParam = {};
        that.i18n = $this.data("i18n");
        initDialog();
        initLayout();
        initEvent();
        initComponent();
        loadBiWorkspaceList();
        selectAppRender();
    };

    init();

});
